package com.yiyi.credit.manage.abutment.mapper;

import com.yiyi.credit.manage.abutment.common.mapper.CommonMapper;
import com.yiyi.credit.manage.abutment.provider.SubProductProvider;
import com.yiyi.credit.manage.model.entity.SubProduct;
import com.yiyi.credit.manage.model.po.ProductPo;
import com.yiyi.credit.manage.model.vo.MainProductApplicationVo;
import com.yiyi.credit.manage.model.vo.SubProductVo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import java.math.BigDecimal;
import java.util.List;


public interface SubProductMapper extends CommonMapper<SubProduct> {

    @SelectProvider(type = SubProductProvider.class, method = "queryList")
    @ResultType(value = SubProductVo.class)
    List<SubProductVo> queryList(@Param("t") SubProduct subProduct, @Param("v") ProductPo productPo);

    @SelectProvider(type = SubProductProvider.class, method = "queryApplyListByParams")
    List<MainProductApplicationVo> queryApplyListByParams(@Param("param") ProductPo param);

    @SelectProvider(type = SubProductProvider.class, method = "selectSubProductStock")
    BigDecimal selectSubProductStock(@Param("productStatus") int productStatus);

    @Select(" select id,product_name productName from sub_product where product_name = #{productName} and is_deleted = 0 ")
    List<SubProduct> queryListByProductName(@Param("productName") String productName);

    @Select("select id, current_inventory currentInventory from sub_product where id = (select product_id from asset_allot_info "
            + "where asset_id = #{assetId})")
    SubProduct selectByAssetId(Long assetId);

    @Select(" select sum(t.nm) from ( " +
            "  select sum(not_matched_amount) nm from investment_record where sub_product_id=#{spid} " +
            "  union all " +
            "  select ifnull(sum(ifnull(not_matched_amount, 0)),0) nm from repayment_detail where sub_product_id=#{spid} " +
            "  ) t")
    BigDecimal selectNotMatchedAmount(@Param("spid") Long subProductId);

    @Select("  select sum(t.nm) from ( " +
            "  select sum(investment_amount - not_matched_amount) nm from investment_record where sub_product_id=#{spid} " +
            "  union all " +
            "  select ifnull(sum(ifnull(repayment_amount - not_matched_amount, 0)),0) nm from repayment_detail where sub_product_id=#{spid} " +
            "  ) t")
    BigDecimal selectMatchedAmount(@Param("spid") Long subProductId);

    @Select("select ifnull(sum(ifnull(surplus_match_amount, 0)), 0) from creditor_right where status=2 and sub_product_id=#{spid}")
    BigDecimal selectReleasedAmount(@Param("spid") Long subProductId);
}
